package xgrammar;

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Arrays;

import org.w3c.xqparser.SimpleNode;
import org.w3c.xqparser.XParserVisitor;

public class vxpPrintXML implements XParserVisitor
{
    public static int indentAmount=3;

    public Object visit(SimpleNode sn, Object o)
    {
        Integer a=(Integer)o;
        String value=sn.getValue();
        char[] padding=new char[a*indentAmount];

        /* Ignore the START node */
        if (sn.toString().equals("START"))
        {
            sn.childrenAccept(this, o);
            return o;
        }

        Arrays.fill(padding, ' ');

        if ((value!=null) && (value.length()>0))
            System.out.print(new String(padding)+"<"+sn.toString()+
                    " value=\""+forXML(value.toString())+"\"");
        else
            System.out.print(new String(padding)+"<"+sn.toString());


        int children=sn.jjtGetNumChildren();

        if (children>0)
        {
            System.out.print(">\n");
            for (int i=0; i<sn.jjtGetNumChildren();i++)
            {
                SimpleNode child=(SimpleNode)sn.jjtGetChild(i);

                if (child!=null)
                    child.jjtAccept(this, a+1);
            }
            System.out.print(new String(padding)+"</"+sn.toString()+">\n");
        }
        else
            System.out.print("/>\n");

        return o;
    }

    /** Escapes a string for XML.
     * @see http://www.javapractices.com/topic/TopicAction.do?Id=96
     * @param aText The String to escape
     * @return String
     */
    public static String forXML(String aText) {
        final StringBuilder result = new StringBuilder();
        final StringCharacterIterator iterator = new StringCharacterIterator(aText);
        char character = iterator.current();
        while (character != CharacterIterator.DONE) {
            if (character == '<') {
                result.append("&lt;");
            } else if (character == '>') {
                result.append("&gt;");
            } else if (character == '\"') {
                result.append("&quot;");
            } else if (character == '\'') {
                result.append("&#039;");
            } else if (character == '&') {
                result.append("&amp;");
            } else {
                //the char is not a special one
                //add it to the result as is
                result.append(character);
            }
            character = iterator.next();
        }
        return result.toString();
    }
}
